define(['element'], function(ele) {
    let allPatches
    let index = 0

    function patch(node, patches) {
        allPatches = patches
        walk(node)
    }

    function walk(node) {
        let current = allPatches[index++]
        let childNodes = node.childNodes

        childNodes.forEach(child => walk(child)) // 同样采用深度优先遍历，对应diff时的patch

        if (current) {
            doPatch(node, current)
        }
    }

    function doPatch(node, patches) {
        patches.forEach(patch => {
            switch (patch.type) {
                case 'ATTR':
                    for (let key in patch.attr) {
                        let value = patch.attr[key]
                        if (value) {
                            ele.setAttr(node, key, value)
                        } else {
                            node.removeAttribute(key)
                        }
                    }
                    break
                case 'TEXT':
                    node.textContent = patch.text
                    break
                case 'REPLACE':
                    let newNode = patch.newNode
                    newNode = (newNode instanceof Element) ? ele.render(newNode) : document.createTextNode(newNode)
                    node.parentNode.replaceChild(newNode, node)
                case 'REMOVE':
                    node.parentNode.removeChild(node)
                    break
                default:
                    break
            }
        })
    }

    return {
        patch
    }
})